package cn.lix.sc.rpc.client.impl.rpc;

import cn.lix.sc.rpc.impl.common.exception.SystemException;
import cn.lix.sc.rpc.impl.common.utils.SpringContextUtil;
import feign.*;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.form.FormEncoder;
import feign.form.spring.SpringFormEncoder;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import feign.slf4j.Slf4jLogger;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

/**
 * 增强的Feign构建器，支持多种内容类型和Jackson序列化
 * @author lix
 * @date 2024
 */
public class EnhancedFeignBuilder {

    private static Retryer retryer;
    private static Encoder encoder;
    private static Decoder decoder;
    private static Logger.Level level;
    private static Client client;
    private static Logger logger;
    private static List<RequestInterceptor> feignRequestInterceptors;

    /**
     * 创建增强的Feign构建器
     */
    public static Feign.Builder createEnhancedFeignBuilder(int connectTimeout, int readTimeout) {
        return Feign.builder()
                .retryer(getRetryer())
                .decoder(getDecoder())
                .encoder(getEnhancedEncoder()) // 使用增强编码器
                .logger(getLogger())
                .options(new Request.Options(connectTimeout, readTimeout))
                .client(getClient())
                .requestInterceptors(getFeignRequestInterceptor())
                .logLevel(getLoggerLevel());
    }

    /**
     * 创建传统的Feign构建器（向后兼容）
     */
    public static Feign.Builder createFeignBuilder(int connectTimeout, int readTimeout) {
        return Feign.builder()
                .retryer(getRetryer())
                .decoder(getDecoder())
                .encoder(getEncoder())
                .logger(getLogger())
                .options(new Request.Options(connectTimeout, readTimeout))
                .client(getClient())
                .requestInterceptors(getFeignRequestInterceptor())
                .logLevel(getLoggerLevel());
    }

    private static Retryer getRetryer() {
        if (retryer == null) {
            try {
                retryer = SpringContextUtil.getBean(Retryer.class);
            } catch (Exception e) {
                retryer = Retryer.NEVER_RETRY; // 默认不重试
            }
        }
        return retryer;
    }

    /**
     * 获取增强编码器，支持multipart/form-data
     */
    private static Encoder getEnhancedEncoder() {
        try {
            // 尝试从Spring容器获取编码器
            Encoder springEncoder = SpringContextUtil.getBean(Encoder.class);
            if (springEncoder != null) {
                // 如果Spring容器中已经有SpringFormEncoder，直接使用
                if (springEncoder instanceof SpringFormEncoder) {
                    return springEncoder;
                }
                // 如果是FormEncoder，也直接使用
                if (springEncoder instanceof FormEncoder) {
                    return springEncoder;
                }
                // 如果是其他编码器，包装成SpringFormEncoder
                return new SpringFormEncoder(springEncoder);
            }
        } catch (Exception ignored) {
            // 忽略异常，使用默认配置
        }

        // 创建Spring支持的表单编码器，完美处理multipart/form-data
        return new SpringFormEncoder(new JacksonEncoder());
    }

    private static Encoder getEncoder() {
        if (encoder == null) {
            try {
                encoder = SpringContextUtil.getBean(Encoder.class);
            } catch (Exception e) {
                encoder = new JacksonEncoder(); // 使用Jackson替代FastJSON
            }
        }
        return encoder;
    }

    private static Decoder getDecoder() {
        if (decoder == null) {
            try {
                decoder = SpringContextUtil.getBean(Decoder.class);
            } catch (Exception e) {
                decoder = new JacksonDecoder(); // 使用Jackson替代FastJSON
            }
        }
        return decoder;
    }

    private static Logger getLogger() {
        if (logger == null) {
            try {
                logger = SpringContextUtil.getBean(Logger.class);
            } catch (Exception e) {
                logger = new Slf4jLogger();
            }
        }
        return logger;
    }

    private static Logger.Level getLoggerLevel() {
        if (level == null) {
            try {
                level = SpringContextUtil.getBean(Logger.Level.class);
            } catch (Exception e) {
                level = Logger.Level.BASIC; // 默认基础日志级别
            }
        }
        return level;
    }

    private static Client getClient() {
        if (client == null) {
            try {
                client = SpringContextUtil.getBean(Client.class);
            } catch (Exception e) {
                client = new Client.Default(null, null);
            }
        }
        return client;
    }

    private static List<RequestInterceptor> getFeignRequestInterceptor() {
        if (feignRequestInterceptors == null) {
            try {
                List<RequestInterceptor> interceptors = SpringContextUtil.getBeansForType(RequestInterceptor.class);
                if (!CollectionUtils.isEmpty(interceptors)) {
                    feignRequestInterceptors = interceptors;
                } else {
                    feignRequestInterceptors = Collections.emptyList();
                }
            } catch (Exception e) {
                feignRequestInterceptors = Collections.emptyList();
            }
        }
        return feignRequestInterceptors;
    }

    /**
     * 重置缓存（用于测试）
     */
    public static void resetCache() {
        retryer = null;
        encoder = null;
        decoder = null;
        level = null;
        client = null;
        logger = null;
        feignRequestInterceptors = null;
    }
} 